extends Control

@export var stats: Stats

@onready var energy_shield_bar: TextureProgressBar = $Left/EnergyShieldBar
@onready var structural_strength_bar: TextureProgressBar = $Left/EnergyShieldBar/StructuralStrengthBar
@onready var energy_bar: TextureProgressBar = $Right/EnergyBar
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var left_animation_player: AnimationPlayer = $Left/LeftAnimationPlayer
@onready var right_animation_player: AnimationPlayer = $Right/RightAnimationPlayer
@onready var left: Control = $Left
@onready var right: Control = $Right

func _ready() -> void:
	
	stats.energy_shield_changed.connect(update_energy_shield)
	update_energy_shield(true)
	
	stats.structural_strength_changed.connect(update_structural_strength)
	update_structural_strength(true)
	
	stats.energy_changed.connect(update_energy)
	update_energy()
	
	tree_exited.connect(func ():
		stats.energy_shield_changed.disconnect(update_energy_shield)
		stats.structural_strength_changed.disconnect(update_structural_strength)
		stats.energy_changed.disconnect(update_energy)
		)

func update_energy_shield(skip_anim: bool = false) -> void:
	var percentage := stats.energy_shield / stats.max_energy_shield
	
	if skip_anim:
		energy_shield_bar.value = percentage
	else:
		create_tween().tween_property(energy_shield_bar, "value", percentage, 0.5)
	
	if percentage == 1:
		hide_left_UI()
	elif left.modulate.a == 0:
		show_left_UI()

func update_structural_strength(skip_anim: bool = false) -> void:
	var percentage := stats.structural_strength / stats.max_structural_strength
	
	if skip_anim:
		structural_strength_bar.value = percentage
	else:
		create_tween().tween_property(structural_strength_bar, "value", percentage, 0.5)

func update_energy() -> void:
	var percentage := stats.energy / stats.max_energy
	
	energy_bar.value = percentage
	
	if percentage == 1:
		hide_right_UI()
	elif left.modulate.a == 0:
		show_right_UI()

func show_UI() -> void:
	modulate.a = 1

func hide_UI(skip_anim: bool = false) -> void:
	if skip_anim:
		modulate.a = 0
	else:
		animation_player.play("hide_ui")

func show_left_UI() -> void:
	left.modulate.a = 1

func hide_left_UI(skip_anim: bool = false) -> void:
	if skip_anim:
		left.modulate.a = 0
	else:
		left_animation_player.play("hide_left_ui")

func show_right_UI() -> void:
	right.modulate.a = 1

func hide_right_UI(skip_anim: bool = false) -> void:
	if skip_anim:
		right.modulate.a = 0
	else:
		right_animation_player.play("hide_right_ui")
